#include "util.hpp"
#include <cstdio>
#include <vector>
#include <functional>

using func_t = function<void ()>;

#define INIT(v) do{\
    v.push_back(printLog);\
    v.push_back(download);\
    v.push_back(executeSql);\
}while(0)

#define EXEC_OTHER(cbs) do{\
    for(auto const &cb : cbs) cb();\
}while(0)

int main()
{
    vector<func_t> cbs;
    INIT(cbs);

    setNonBlock(0);
    char buffer[1024];
    while(true)
    {
        // printf(">>> ");
        // fflush(stdout);
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if(s > 0)
        {
            buffer[s - 1] = 0;
            cout << "echo# " << buffer << endl;
        }
        else if(s == 0)
        {
            cout << "read end" << endl;
            break;
        }
        else
        {
            // 1. 当我不输入的时候,底层没有数据,算错误吗? 不算错误,只不过以错误的形式返回
            // 2. 我如何区分到底是真的错误还是没有数据? 单纯依靠返回值,无法区分
            // cout << "EAGAIN" << EAGAIN << "EWOULDBLOCK" << EWOULDBLOCK << endl;

            if(errno == EAGAIN)
            {
                cout << "没有错误,只是没有数据" << endl;
                EXEC_OTHER(cbs);
            }
            else if(errno == EINTR)
            {
                continue;
            }
            else
            {
                cout << "s : " << s << " errno: " << strerror(errno) << endl;
                break;
            }
        }
        
        sleep(1);
    }
}